package com.rn.gypsophila.dsalg.string;

/**
 * 题目：编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 ""。
 * 链接：<a href="https://leetcode.cn/leetbook/read/array-and-string/ceda1/">...</a>
 *
 * @author 然诺
 * @since 2023/3/12
 */
public class LongestCommonPrefix {

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        StringBuilder prefixSb = new StringBuilder();
        for (int i = 0; i < strs[0].length(); i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (i >= strs[j].length() || c != strs[j].charAt(i)) {
                    return prefixSb.toString();
                }
            }
            prefixSb.append(c);
        }
        return prefixSb.toString();
    }

    public static void main(String[] args) {
        String[] strs1  = new String[]{"flower","flow","flight"};
        String[] strs2  = new String[]{"dog","racecar","car"};
        String[] strs3  = new String[]{"ab", "a"};
        System.out.println(longestCommonPrefix(strs1));
        System.out.println(longestCommonPrefix(strs2));
        System.out.println(longestCommonPrefix(strs3));
    }
}
